import axios from 'axios';
import common from './common/common'
import constants from "./common/constants";
axios.defaults.timeout = 10*60*1000
let instance = null
let fetchResTime = 0
const axiosInstance = () => {
    if (!instance) {
        instance = axios.create({
            baseURL: '',
            headers: { 'Content-Type': 'application/json' }, // x-www-form-urlencoded
        })
    }
    instance.interceptors.request.use(
        (config) => {
            const token = common.getLocalToken();
            const user = common.getLocalUser();
            if (token) {
                config.headers = config.headers || {}
                config.headers[constants.LocalTokenKey] = token
                config.headers['uid'] = user.userId
            }
            return config
        },
        (error) => Promise.reject(error)
    )
    instance.interceptors.response.use(
        (response) => {
            if (response.status === 200) {
                const res = response.data
                if (res && res.code === 401) {
                    let ts = +new Date()
                    if (ts - fetchResTime >= 300) {
                        fetchResTime = ts
                        const router = window.__router
                        if (router) {
                            router.replace('/login')
                        }
                    }
                    return Promise.reject()
                } else {
                    return Promise.resolve(res)
                }
            }
            return Promise.resolve(response)
        },
        (error) => {
            return Promise.reject(error)
        }
    )
    return instance
}
export default axiosInstance()
